import { cloneDeep, includes } from 'lodash-es'
import { http } from '@/utils/http'
import { ElMessage, ElMessageBox } from 'element-plus'
import _ from 'lodash-es'



export const useOrderStore = () => {
    const router = useRouter()
    const languageJson = inject('languageJson')
    const languageType = inject('languageType')
    const state = reactive({
        activestatus: 0,
        status: [{
            value: 0,
            label: languageJson.value.home.all,
            ncount: 0
        }, {
            value: 1,
            label: languageJson.value.order.reservation,
            count: 0
        }, {
            value: 2,
            label: languageJson.value.order.unresolved,
            count: 0
        }, {
            value: 3,
            label: languageJson.value.order.alreadysettled,
            count: 0
        }, {
            value: 4,
            label: languageJson.value.order.settlementError,
            count: 0
        }, {
            value: 5,
            label: languageJson.value.home.cancel,
            count: 0
        }, {
            value: 6,
            label: languageJson.value.home.alreadyComplete,
            count: 0
        }],

        leaguefilter: [],
        matchfilter: [],

        filterdialog: false,
        filterForm: {
            sport_type: "soccer",
            order_status: 0,
            league_name: "all",
            homeaway: 'all',
            home_away: {
                home: "",
                away: ""
            },
            order_time: [],
            begin_time: "2024-11-01 04:46:12",
            end_time: "2024-11-29 04:46:12",
            match_time: [],
            match_begin_time: "2024-11-01 04:46:12",
            match_end_time: "2024-11-29 04:46:12",
            page: 1,
            page_size: 20
        },

        orderLoading: false,
        orderList: [],
        orderListtotal: 0,
        textmap: {
            soccer_handicap: {
                ce_odds_data: languageJson.value.home.corner,
                odds_data: '',
                pc_odds_data: languageJson.value.home.card,

                full: languageJson.value.home.full,
                half: languageJson.value.home.half,

                M: '',
                R: languageJson.value.home.letballgo,
                OU: languageJson.value.home.ou,
                OUH: languageJson.value.home.homeGoalTotal,
                OUC: languageJson.value.home.awayGoalTotal,
                CRS: ''
            },
            basketball_handicap: {
                ce_odds_data: languageJson.value.home.corner,
                odds_data: '',
                pc_odds_data: languageJson.value.home.card,
                // pd_odds_data: '波胆',

                full: languageJson.value.home.full,
                half: languageJson.value.home.half,

                section1: languageJson.value.home.section1,
                section2: languageJson.value.home.section2,

                M: '',
                R: languageJson.value.home.letballgo,
                OU: languageJson.value.home.ou,
                OUH: languageJson.value.home.basketballFirstScore,
                OUC: languageJson.value.home.basketballSecondScore,
                CRS: ''
            },
        }



    })

    const getleaguefilter = () => {
        let body = {
            params: {
                sport_type: state.filterForm.sport_type
            }
        }
        http.get('/order/league_filter', body).then((res) => {
            state.leaguefilter = res.data
            changeleaguename()
        })
    }

    const getorderfiltercount = () => {
        let body = {
            sport_type: state.filterForm.sport_type,
            league_name: state.filterForm.league_name,
            home_away: {
                home: "",
                away: ""
            },
            begin_time: state.filterForm.order_time[0],
            end_time: state.filterForm.order_time[1],
            match_begin_time: state.filterForm.match_time[0],
            match_end_time: state.filterForm.match_time[1],
        }
        if (body.league_name == 'all') {
            delete body.league_name
        }
        if (state.filterForm.homeaway == 'all') {
            delete body.home_away
        } else {
            let parts = state.filterForm.homeaway.split("-vs-");
            let beforeVs = parts[0];
            let afterVs = parts[1];
            state.matchfilter.forEach(item => {
                if (item.home == beforeVs && item.away == afterVs) {
                    body.home_away = item
                }
            });
        }
        http.post('/order/order_filter_count', body).then((res) => {
            let a = [{
                value: 0,
                label: languageJson.value.home.all,
                count: res.data.all_task_count
            }, {
                value: 1,
                label: languageJson.value.order.reservation,
                count: res.data.reservation_task_count
            }, {
                value: 2,
                label: languageJson.value.order.unresolved,
                count: res.data.not_check_task_count
            }, {
                value: 3,
                label: languageJson.value.order.alreadysettled,
                count: res.data.check_success_task_count
            }, {
                value: 4,
                label: languageJson.value.order.settlementError,
                count: res.data.check_error_task_count
            }, {
                value: 5,
                label: languageJson.value.home.cancel,
                count: res.data.cancel_task_count
            }, {
                value: 6,
                label: languageJson.value.home.alreadyComplete,
                count: res.data.complete_task_count
            }]
            state.status = a

        })
    }

    const changeactivestatus = (value) => {
        state.activestatus = value
        state.filterForm.order_status = state.activestatus
        getorderList()
    }

    const openOrderfilter = () => {
        state.filterdialog = true

    }

    const changeleaguename = () => {
        let a = []
        if (state.filterForm.league_name == 'all') {
            Object.keys(state.leaguefilter).forEach(key => {
                a = [...a, ...state.leaguefilter[key].list]
            });
        } else {
            a = state.leaguefilter[state.filterForm.league_name].list
        }
        state.matchfilter = a
        state.filterForm.homeaway = 'all'
    }

    const getTimerange = () => {
        let a = getBeijingWeekDates()
        state.filterForm.begin_time = a.start
        state.filterForm.end_time = a.end
        state.filterForm.match_begin_time = a.start
        state.filterForm.match_end_time = a.end
        state.filterForm.order_time = [a.start, a.end]
        state.filterForm.match_time = [a.start, a.end]


    }

    const getBeijingWeekDates = () => {
        const now = new Date();

        // 获取当前年份和月份
        const year = now.getFullYear();
        const month = now.getMonth(); // 当前月份（从0开始，即0是1月，11是12月）

        // 获取本月1号的日期
        const firstDayOfMonth = new Date(year, month, 1);
        firstDayOfMonth.setHours(12, 0, 0, 0); // 设置为12:00:00中午

        // 获取本月最后一天的日期
        const lastDayOfMonth = new Date(year, month + 1, 0); // 获取下月的第0天，即为本月的最后一天
        lastDayOfMonth.setHours(12, 0, 0, 0); // 设置为12:00:00中午

        // 格式化日期函数
        const formatDate = (date) => {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        };

        // 返回日期范围
        let result = {
            start: `${formatDate(firstDayOfMonth)} 12:00:00`,
            end: `${formatDate(lastDayOfMonth)} 12:00:00`
        };

        return result;
    }

    const filterReset = () => {
        state.filterForm = {
            sport_type: "soccer",
            order_status: 0,
            league_name: "all",
            homeaway: 'all',
            home_away: {
                home: "",
                away: ""
            },
            order_time: [],
            begin_time: "2024-11-01 04:46:12",
            end_time: "2024-11-29 04:46:12",
            match_time: [],
            match_begin_time: "2024-11-01 04:46:12",
            match_end_time: "2024-11-29 04:46:12",
            page: 1,
            page_size: 20
        }
        state.activestatus = state.filterForm.order_status
        state.filterdialog = false
        initData()
    }

    const clicksubmit = () => {
        state.filterdialog = false
        state.activestatus = state.filterForm.order_status
        getorderList()

    }

    const getorderList = () => {
        state.orderLoading = true
        let body = {
            sport_type: state.filterForm.sport_type,
            order_status: state.filterForm.order_status,
            league_name: state.filterForm.league_name,
            home_away: {
                home: "",
                away: ""
            },
            begin_time: state.filterForm.order_time[0],
            end_time: state.filterForm.order_time[1],
            match_begin_time: state.filterForm.match_time[0],
            match_end_time: state.filterForm.match_time[1],
            page: state.filterForm.page,
            page_size: state.filterForm.page_size
        }
        if (body.league_name == 'all') {
            delete body.league_name
        }
        if (state.filterForm.homeaway == 'all') {
            delete body.home_away
        } else {
            let parts = state.filterForm.homeaway.split("-vs-");
            let beforeVs = parts[0];
            let afterVs = parts[1];
            state.matchfilter.forEach(item => {
                if (item.home == beforeVs && item.away == afterVs) {
                    body.home_away = item
                }
            });
        }
        http.post('/order/order_list_bytask', body).then((res) => {
            console.log(res);
            state.orderList = res.data.list
            state.orderListtotal = res.data.total
            state.orderLoading = false
        })


    }

    const gethandicapname = (sport_type, pk_odds_key) => {
        let pkoddskeyarr = pk_odds_key.split(':');
        let handicap = sport_type == "soccer" ? state.textmap.soccer_handicap : state.textmap.basketball_handicap
        let a = {}
        let handicapname = []
        let handicapnamestr = ''

        if (pkoddskeyarr[0] == 'C') {
            handicapname.push(`${handicap[[pkoddskeyarr[1]]]}${languageJson.value.home.corner}`)
            if (pkoddskeyarr[2] == 'OU') {
                if (pkoddskeyarr[pkoddskeyarr.length - 1] == '0') {
                    handicapname.push(languageJson.value.home.over)
                } else {
                    handicapname.push(languageJson.value.home.under)
                }
            } else {
                handicapname.push(handicap[[pkoddskeyarr[2]]])
            }
        } else if (pkoddskeyarr[0] == 'F') {
            handicapname.push(`${handicap[[pkoddskeyarr[1]]]}${languageJson.value.home.card}`)
            if (pkoddskeyarr[2] == 'OU') {
                if (pkoddskeyarr[pkoddskeyarr.length - 1] == '0') {
                    handicapname.push(languageJson.value.home.over)
                } else {
                    handicapname.push(languageJson.value.home.under)
                }
            } else {
                handicapname.push(handicap[[pkoddskeyarr[2]]])
            }
        } else {
            handicapname.push(`${handicap[[pkoddskeyarr[0]]]}`)

            if (pkoddskeyarr[1] == 'OU') {
                if (pkoddskeyarr[pkoddskeyarr.length - 1] == '0') {
                    handicapname.push(languageJson.value.home.over)
                } else {
                    handicapname.push(languageJson.value.home.under)
                }
            } else {

                if (pkoddskeyarr[1] == 'R') {
                    if (pkoddskeyarr[pkoddskeyarr.length - 1] == '0') {
                        handicapname.push(languageJson.value.home.home)
                    } else {
                        handicapname.push(languageJson.value.home.away)
                    }
                }
                if (pkoddskeyarr[1] != 'M') {
                    handicapname.push(handicap[pkoddskeyarr[1]])
                } else {
                    if (pkoddskeyarr[3] == '0') {
                        handicapname.push([`${languageJson.value.home.home}${languageJson.value.home.win}`])
                    }
                    if (pkoddskeyarr[3] == '1') {
                        handicapname.push([`${languageJson.value.home.away}${languageJson.value.home.win}`])
                    }
                    if (pkoddskeyarr[3] == '2') {
                        handicapname.push([languageJson.value.home.draw])
                    }
                }
                if (pkoddskeyarr[1] == 'OUH' || pkoddskeyarr[1] == 'OUC') {
                    if (pkoddskeyarr[pkoddskeyarr.length - 1] == '0') {
                        handicapname.push(languageJson.value.home.over)
                    } else {
                        handicapname.push(languageJson.value.home.under)
                    }
                }


            }
        }

        if (pkoddskeyarr[1] != 'M') {
            handicapname.push(pkoddskeyarr[pkoddskeyarr.length - 2])
        }
        handicapnamestr = handicapname.join(':');
        return handicapnamestr
    }


    onMounted(async () => {
        initData()
    })

    onUnmounted(() => {
    })


    async function initData() {
        getleaguefilter()

        getTimerange()
        getorderList()
        getorderfiltercount()
    }


    return {
        state,

        changeactivestatus,
        openOrderfilter,
        changeleaguename,
        filterReset,
        clicksubmit,
        getorderList,
        gethandicapname

    }
}
